import pickle
import load
import q3
import numpy as np

C1mean=int(np.array(q3.C1Member).mean())
C2mean=int(np.array(q3.C2Member).mean())
C3mean=int(np.array(q3.C3Member).mean())

model = pickle.load(open('q3dingjia.pkl', 'rb'))
print(model.get_weights())

allJing=[]
allWei=[]
for i in range(1,2067):
    allJing.append(float(load.getCellT2(i, load.jingdu)))
    allWei.append(float(load.getCellT2(i, load.weidu)))

C1TaskJing,C2TaskJing,C3TaskJing,C1TaskWei,C2TaskWei,C3TaskWei,allDist=q3.classTask(allJing,allWei)
C1JingWei=[(C1TaskJing[i],C1TaskWei[i]) for i in range(len(C1TaskWei))]
C2JingWei=[(C2TaskJing[i],C2TaskWei[i]) for i in range(len(C2TaskWei))]
C3JingWei=[(C3TaskJing[i],C3TaskWei[i]) for i in range(len(C3TaskWei))]

allPack=[]
packNum=0
distThreshold=(10/111)**2
print(distThreshold)
class pack:
    def __init__(self,cluCenter:int,posi):
        global packNum
        self.no=packNum
        packNum+=1
        self.allPos=[]
        self.allPos.append(posi)
        self.cluCenter=cluCenter
        if cluCenter==0:
            self.dist = q3.dist(posi[0], posi[1], q3.estimator.cluster_centers_[0, 0],
                                q3.estimator.cluster_centers_[0, 1])
        elif cluCenter==1:
            self.dist = q3.dist(posi[0], posi[1], q3.estimator.cluster_centers_[1, 0],
                                q3.estimator.cluster_centers_[1, 1])
        else:
            self.dist = q3.dist(posi[0], posi[1], q3.estimator.cluster_centers_[2, 0],
                                q3.estimator.cluster_centers_[2, 1])
        self.price = model.predict(np.array([self.dist]))[0, 0] ** 2
        allPack.append(self)

    def add(self,pos,dist:float):
        newdist=self.dist+dist
        if newdist>=distThreshold or dist==100:
            return False
        elif self.cluCenter==0 and len(self.allPos)>=C1mean:
            return False
        elif self.cluCenter==1 and len(self.allPos)>=C2mean:
            return False
        elif self.cluCenter==2 and len(self.allPos)>=C3mean:
            return False
        else:
            self.allPos.append(pos)
            self.dist+=dist
            self.price = model.predict(np.array([self.dist]))[0, 0] ** 2
            return True

    def output(self):
        content=''
        for pos in self.allPos:
            content+= str(pos[0]) +',' + str(pos[1]) +',' + str(self.no) +',' + str(self.price) + '\n'
        return content

def getDist(pos1, pos2):
    if pos1 is None:
        return 100
    elif pos2 is None:
        return 100
    else:
        d=q3.dist(pos1[0],pos1[1],pos2[0],pos2[1])
        if d==0:
            return 100 # 和自己不算
        else:
            return d

def findSub(val,list):
    for i in range(len(list)):
        if list[i]==val:
            return i
    return None

def findSetNone(val,list):
    sub=findSub(val,list)
    if sub:
        list[sub]=None

def doPack(code,jingwei):
    packing = None
    for posi in jingwei:
        if posi is None:
            continue
        while True:
            posj = min(jingwei, key=lambda x: getDist(posi, x))
            d = getDist(posi, posj)

            if packing is None:
                packing = pack(code, posi)
                findSetNone(posi, jingwei)  # 添加成功立刻置None

            r = packing.add(posj, d)

            if not r:  # 添加失败（j没添加进去）
                packing = None
                break
            else:
                findSetNone(posj, jingwei)  # 添加成功立刻置None
                posi = posj  # j添加进去了，准备找链路的下个节点

doPack(0,C1JingWei)
doPack(1,C2JingWei)
doPack(2,C3JingWei)

content=''
for i in allPack:
    content+=i.output()
load.writeFile('打包结果.csv',content)
